<template>
  <div class="app-container">
    <!-- 顶部操作栏 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="模板名称">
            <el-input v-model="searchForm.templateName" placeholder="模板名称" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="厂商名称">
            <el-input v-model="searchForm.vendor" placeholder="厂商名称" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="模板型号">
            <el-input v-model="searchForm.model" placeholder="模板型号" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="是否推送">
            <el-select v-model="searchForm.pushEnabled" placeholder="是否推送" clearable>
              <el-option label="不推送" value="0"></el-option>
              <el-option label="推送" value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="6">
          <el-form-item label="是否启用">
            <el-select v-model="searchForm.enabled" placeholder="是否启用" clearable>
              <el-option label="禁用" value="0"></el-option>
              <el-option label="启用" value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="14" class="text-left">
          <el-button type="primary" @click="handleSearch" icon="search">搜索</el-button>
          <el-button @click="handleReset">
            <el-icon>
              <Refresh />
            </el-icon>重置
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- IoT设备模板表格 -->
    <el-card class="mt-1">
      <el-button type="primary" @click="showCreateDialog">
        <el-icon>
          <Plus />
        </el-icon>新增
      </el-button>
      <el-table v-loading="loading" :data="tableData" border align="center" class="iot-template-table mt-2">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="templateName" label="模板名称" align="center" />
        <el-table-column prop="vendor" label="厂商名称" align="center" />
        <el-table-column prop="model" label="设备型号" align="center" />
        <el-table-column prop="pushEnabled" label="是否推送" align="center">
          <template #default="{ row }">{{ row.pushEnabled === 1 ? '是' : '否' }}</template>
        </el-table-column>
        <el-table-column prop="enabled" label="是否启用" align="center">
          <template #default="{ row }">{{ row.enabled === 1 ? '启用' : '禁用' }}</template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" align="center" width="180" />
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="text" @click="showDetailDialog(row.id)">详情</el-button>
            <el-button type="text" @click="showEditDialog(row.id)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination class="mt-2" v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50]" layout="total, sizes, prev, pager, next, jumper" :total="total"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="`${isEditMode ? '编辑' : '新增'}IoT设备模板`" width="600px"
      @closed="handleDialogClosed">
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="120px">
        <el-form-item label="模板名称" prop="templateName">
          <el-input v-model="formData.templateName" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="厂家名称" prop="vendor">
          <el-input v-model="formData.vendor" placeholder="请输入厂家名称" />
        </el-form-item>
        <el-form-item label="设备型号" prop="model">
          <el-input v-model="formData.model" placeholder="请输入设备型号" />
        </el-form-item>
        <el-form-item label="接入服务器ip" prop="serverIp">
          <el-input v-model="formData.serverIp" placeholder="请输入ip地址" />
        </el-form-item>
        <!-- 问题2修复：端口输入框加type="number" -->
        <el-form-item label="接入服务器端口" prop="serverPort">
          <el-input v-model.number="formData.serverPort" placeholder="请输入端口号" type="number" min="1" max="65535" />
        </el-form-item>
        <el-form-item label="接入协议" prop="serverProtocol">
          <el-input v-model="formData.serverProtocol" placeholder="请输入接入协议" />
        </el-form-item>
        <el-form-item label="解析协议配置" prop="parseSpec">
          <el-input v-model="formData.parseSpec" placeholder="请输入解析协议配置" />
        </el-form-item>

        <el-form-item label="是否推送" prop="pushEnabled">
          <el-select v-model="formData.pushEnabled" placeholder="请选择是否推送">
            <el-option label="不推送" value="0"></el-option>
            <el-option label="推送" value="1"></el-option>
          </el-select>
        </el-form-item>

        <!-- 优化1：未推送时隐藏推送相关输入框（v-if控制） -->
        <template v-if="formData.pushEnabled === '1'">
          <!-- 问题1修复：推送IP校验（动态required） -->
          <el-form-item label="推送服务器IP" prop="pushServerIp">
            <el-input v-model="formData.pushServerIp" placeholder="请输入推送服务器IP" />
          </el-form-item>
          <!-- 问题1+2修复：推送端口校验+type="number" -->
          <el-form-item label="推送服务器端口" prop="pushServerPort">
            <el-input v-model.number="formData.pushServerPort" placeholder="请输入推送服务器端口" type="number" min="1"
              max="65535" />
          </el-form-item>
          <el-form-item label="推送协议" prop="pushProtocol">
            <el-input v-model="formData.pushProtocol" placeholder="请输入推送协议" />
          </el-form-item>
          <el-form-item label="推送数据格式" prop="pushFormat">
            <el-input v-model="formData.pushFormat" placeholder="请输入推送格式" />
          </el-form-item>
        </template>

        <el-form-item label="心跳间隔(秒)" prop="heartbeatSec">
          <el-input v-model.number="formData.heartbeatSec" placeholder="请输入心跳间隔" type="number" min="1" />
        </el-form-item>
        <el-form-item label="接收超时(秒)" prop="recvTimeoutSec">
          <el-input v-model.number="formData.recvTimeoutSec" placeholder="请输入接收超时" type="number" min="1" />
        </el-form-item>
        <el-form-item label="失败重试次数" prop="retryLimit">
          <el-input v-model.number="formData.retryLimit" placeholder="请输入重试次数" type="number" min="0" />
        </el-form-item>
        <el-form-item label="是否启用" prop="enabled">
          <el-select v-model="formData.enabled" placeholder="请选择是否启用">
            <el-option label="禁用" value="0"></el-option>
            <el-option label="启用" value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="IoT设备模板详情" width="800px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="模板ID">{{ detailData.id }}</el-descriptions-item>
        <el-descriptions-item label="模板名称">{{ detailData.templateName }}</el-descriptions-item>
        <el-descriptions-item label="厂家/厂商名称">{{ detailData.vendor }}</el-descriptions-item>
        <el-descriptions-item label="设备型号/系列">{{ detailData.model }}</el-descriptions-item>
        <el-descriptions-item label="接入服务器IP/域名">{{ detailData.serverIp }}</el-descriptions-item>
        <el-descriptions-item label="接入服务器端口">{{ detailData.serverPort }}</el-descriptions-item>
        <el-descriptions-item label="接入协议">{{ detailData.serverProtocol }}</el-descriptions-item>
        <el-descriptions-item label="解析协议配置">{{ detailData.parseSpec }}</el-descriptions-item>
        <el-descriptions-item label="是否启用数据推送">{{ detailData.pushEnabled === 1 ? '是' : '否' }}</el-descriptions-item>
        <el-descriptions-item label="推送服务器IP/域名">{{ detailData.pushServerIp }}</el-descriptions-item>
        <el-descriptions-item label="推送服务器端口">{{ detailData.pushServerPort }}</el-descriptions-item>
        <el-descriptions-item label="推送协议">{{ detailData.pushProtocol }}</el-descriptions-item>
        <el-descriptions-item label="推送数据格式/封包规则">{{ detailData.pushFormat }}</el-descriptions-item>
        <el-descriptions-item label="心跳/保活间隔(秒)">{{ detailData.heartbeatSec }}</el-descriptions-item>
        <el-descriptions-item label="接收超时(秒)">{{ detailData.recvTimeoutSec }}</el-descriptions-item>
        <el-descriptions-item label="失败重试次数上限">{{ detailData.retryLimit }}</el-descriptions-item>
        <el-descriptions-item label="是否启用模板">{{ detailData.enabled === 1 ? '启用' : '禁用' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detailData.createdAt }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ detailData.updatedAt }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Plus, Refresh } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as api from '@/api/park/device/template'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10
})

// 搜索表单
const searchForm = reactive({
  templateName: undefined,
  vendor: undefined,
  model: undefined,
  pushEnabled: undefined,
  enabled: undefined
})

// 表单数据（ref对象，默认值优化）
const formData = ref({
  deviceTemplateId: undefined,
  templateName: '',
  vendor: '',
  model: '',
  serverIp: '',
  serverPort: '',
  serverProtocol: '',
  parseSpec: '',
  pushEnabled: '',
  pushServerIp: '',
  pushServerPort: '',
  pushProtocol: '',
  pushFormat: '',
  heartbeatSec: '',
  recvTimeoutSec: '',
  retryLimit: '',
  enabled: ''
})

// 表单验证规则（修复问题1和问题2）
const rules = reactive({
  templateName: [
    { required: true, message: '模板名称不能为空', trigger: 'blur' }
  ],
  vendor: [
    { required: true, message: '厂家名称不能为空', trigger: 'blur' }
  ],
  model: [
    { required: true, message: '设备型号不能为空', trigger: 'blur' }
  ],
  serverIp: [
    { required: true, message: '服务器ip不能为空', trigger: 'blur' }
  ],
  serverPort: [
    { required: true, message: '端口不能为空', trigger: 'blur' },
    { type: 'number', message: '请输入数字', trigger: 'blur' },
  ],
  serverProtocol: [
    { required: true, message: '接入协议不能为空', trigger: 'blur' }
  ],
  parseSpec: [
    { required: true, message: '解析协议配置不能为空', trigger: 'blur' }
  ],
  pushServerIp: [ // 问题1修复：动态required（函数形式）
    {
      required: () => formData.value.pushEnabled === '1',
      message: '启用推送时，IP不能为空',
      trigger: 'blur'
    }
  ],
  pushServerPort: [ // 问题1+2修复：动态required+数字校验
    {
      required: () => formData.value.pushEnabled === '1',
      message: '启用推送时，端口不能为空',
      trigger: 'blur'
    },
    { type: 'number', message: '请输入数字', trigger: 'blur' },
    { min: 1, max: 65535, message: '端口范围为1-65535', trigger: 'blur' },
    { transform: (value) => Number(value), trigger: 'blur' }
  ],
})

// 表格数据
const tableData = ref([])
const total = ref(0)
const loading = ref(false)

// 对话框控制
const dialogVisible = ref(false)
const isEditMode = ref(false)
const formRef = ref(null)
const detailDialogVisible = ref(false)
const detailData = ref({})


// 初始化数据
onMounted(() => {
  getList()
})

// 获取列表数据
const getList = async () => {
  try {
    loading.value = true
    const res = await api.getIotDeviceTemplateList(queryParams)
    tableData.value = res.rows || []
    total.value = res.total || 0
  } catch (error) {
    console.error('获取列表失败:', error)
    ElMessage.error('获取列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  Object.assign(queryParams, { pageNum: 1, ...searchForm })
  getList()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    templateName: undefined, vendor: undefined, model: undefined,
    pushEnabled: undefined, enabled: undefined
  })
  handleSearch()
}

// 分页大小变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getList()
}

// 当前页变化
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  getList()
}

// 显示新增对话框
const showCreateDialog = () => {
  isEditMode.value = false
  dialogVisible.value = true
}

// 显示编辑对话框（问题3修复：数字转字符串）
const showEditDialog = async (id) => {
  try {
    loading.value = true
    const detailRes = await api.getIotDeviceTemplateDetail(id)
    const data = detailRes.data || {}
    // 问题3修复：将数字转为字符串，匹配el-select的value类型
    formData.value = {
      ...data,
      pushEnabled: data.pushEnabled?.toString() || '0',
      enabled: data.enabled?.toString() || '1',
      // 数字类型字段转为数字（避免输入框显示字符串）
      serverPort: data.serverPort || '',
      pushServerPort: data.pushServerPort || '',
      heartbeatSec: data.heartbeatSec || '',
      recvTimeoutSec: data.recvTimeoutSec || '',
      retryLimit: data.retryLimit || ''
    }
    isEditMode.value = true
    dialogVisible.value = true
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取详情失败')
  } finally {
    loading.value = false
  }
}

// 显示详情对话框
const showDetailDialog = async (id) => {
  try {
    loading.value = true
    const detailRes = await api.getIotDeviceTemplateDetail(id)
    detailData.value = detailRes.data || {}
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取详情失败')
  } finally {
    loading.value = false
  }
}

// 重置表单数据
const resetFormData = () => {
  formData.value = {
    deviceTemplateId: undefined,
    templateName: '',
    vendor: '',
    model: '',
    serverIp: '',
    serverPort: '',
    serverProtocol: '',
    parseSpec: '',
    pushEnabled: '',
    pushServerIp: '',
    pushServerPort: '',
    pushProtocol: '',
    pushFormat: '',
    heartbeatSec: '',
    recvTimeoutSec: '',
    retryLimit: '',
    enabled: ''
  }
}

// 对话框关闭（重置表单）
const handleDialogClosed = () => {
  formRef.value?.resetFields()
  resetFormData()
}

// 提交表单（确保字段类型正确）
const handleSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return

    // 提交数据：将字符串转为数字（匹配后端接口类型）
    const submitData = {
      ...formData.value,
      serverPort: formData.value.serverPort ? Number(formData.value.serverPort) : 0,
      pushServerPort: formData.value.pushServerPort ? Number(formData.value.pushServerPort) : 0,
      heartbeatSec: formData.value.heartbeatSec ? Number(formData.value.heartbeatSec) : 0,
      recvTimeoutSec: formData.value.recvTimeoutSec ? Number(formData.value.recvTimeoutSec) : 0,
      retryLimit: formData.value.retryLimit ? Number(formData.value.retryLimit) : 0,
      pushEnabled: Number(formData.value.pushEnabled),
      enabled: Number(formData.value.enabled)
    }

    try {
      if (isEditMode.value) {
        await api.updateIotDeviceTemplate(submitData)
        ElMessage.success('修改成功')
      } else {
        await api.addIotDeviceTemplate(submitData)
        ElMessage.success('新增成功')
      }
      dialogVisible.value = false
      getList()
    } catch (error) {
      console.error('提交失败:', error)
      ElMessage.error('提交失败')
    }
  })
}
</script>

<style scoped>
.iot-template-table {
  width: 100%;
}

.mt-1 {
  margin-top: 10px;
}

.mt-2 {
  margin-top: 20px;
}

/* 优化数字输入框样式（去除默认箭头） */
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}
</style>